package org.iteye.bbjava.frame.work.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;


/***
 * Strut2Util 类，封装常用方法，以静态地方式调用
 * @author zhang
 * @version v0.1
 * */
public class Struct2Util {

	
	/**获取httpServletRequest对象
	 * @author zhang
	 * @return HttpServletRequest对象
	 * */
	public static HttpServletRequest getHttpServletRequest(){
		HttpServletRequest request = ServletActionContext.getRequest();
		return (HttpServletRequest) request;
	}
	
	/**
	 * 获取所有请求参数
	 * @return
	 */
	public static Map getReuqestParams(){
		HttpServletRequest request = getHttpServletRequest();
		Enumeration<String> enumeration = request.getParameterNames();
		Map<String,String> map = new HashMap();
		while(enumeration.hasMoreElements()){
			String key = enumeration.nextElement();
			map.put(key,request.getParameter(key));
		}
		return map;
	}
	
	
	/**
	 * 上传文件到指定目录下
	 * @author zhang
	 * @param request 请求对象
	 * @param filePath 文件对象
	 * 
	 * */
	public static void toFile(ServletRequest request,File filePath) throws IOException{
		InputStream is = request.getInputStream();
		OutputStream os = new FileOutputStream(filePath);
		int available = is.available();
		byte[] buffer = new byte[1024];
		while( -1 != is.read(buffer) ){
			if(available > buffer.length ){
				os.write(buffer);
			}else{
				int last = (available%buffer.length);
				byte[] bufferLast = new byte[last]; 
				/*	src the source array.
					srcPos starting position in the source array.
					dest the destination array.
					destPos starting position in the destination data.
					length the number of array elements to be copied.
				*/
				System.arraycopy(buffer, 0, bufferLast, 0, last);
				os.write(bufferLast);
			}
		}
	}
	
	public static void getParam(){
		HttpServletRequest request = getHttpServletRequest();
		request.getQueryString();
	}
	
	
}
